package org.example.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.RequiredArgsConstructor;
import org.example.mapper.SyncConfigMapper;
import org.example.model.*;
import org.example.service.PrecisionScheduler;
import org.example.service.SyncService;
import org.springframework.http.ResponseEntity;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * 同步配置管理API
 */
@RestController
@RequestMapping("/api/sync-config")
@RequiredArgsConstructor
@Validated
public class SyncConfigController {

    private final SyncConfigMapper configMapper;
    private final PrecisionScheduler scheduler;
    private final SyncService syncService;

    /**
     * 分页查询配置
     */
    @PostMapping("/page")
    public PageResult<SyncConfig> getConfigByPage(@Valid @RequestBody SyncConfigQuery query) {

        // 使用 PageHelper 进行分页
        PageHelper.startPage(query.getPageNum(), query.getPageSize());
        List<SyncConfig> configs = configMapper.selectByCondition(query);

        // 获取分页信息
        PageInfo<SyncConfig> pageInfo = new PageInfo<>(configs);

        // 返回自定义的分页结果
        return new PageResult<>(
                pageInfo.getTotal(),
                pageInfo.getList(),
                pageInfo.getPageNum(),
                pageInfo.getPageSize(),
                pageInfo.getPages()
        );
    }


    /**
     * 根据ID获取单个配置
     */
    @PostMapping("/detail")
    public ResponseEntity<SyncConfig> getConfig(@RequestParam Long id) {
        SyncConfig config = configMapper.selectById(id);
        return config != null ?
                ResponseEntity.ok(config) :
                ResponseEntity.notFound().build();
    }

    /**
     * 创建新配置
     */
    @PostMapping("/create")
    public ResponseEntity<?> createConfig(@Valid @RequestBody SyncConfig config) {
        // 验证表是否已配置
        if (configMapper.selectByTableName(config.getSourceTable()) != null) {
            return ResponseEntity.badRequest().body("该表已存在同步配置");
        }

        configMapper.insert(config);

        if (config.getEnabled()) {
            scheduler.scheduleTask(config);
        }

        return ResponseEntity.ok(config);
    }

    /**
     * 更新配置
     */
    @PostMapping("/update")
    public ResponseEntity<?> updateConfig(
                                          @Valid @RequestBody SyncConfig config) {
        configMapper.update(config);

        if (config.getEnabled()) {
            scheduler.scheduleTask(config);
        } else {
            scheduler.cancelTask(config.getId());
        }

        return ResponseEntity.ok(config);
    }

    /**
     * 更新配置启用状态
     */
    @PostMapping("/update-status")
    public ResponseEntity<?> updateStatus(@RequestParam Long id,
                                          @RequestParam Boolean enabled) {
        SyncConfig config = configMapper.selectById(id);
        if (config == null) {
            return ResponseEntity.notFound().build();
        }

        config.setEnabled(enabled);
        configMapper.update(config);

        if (enabled) {
            scheduler.scheduleTask(config);
        } else {
            scheduler.cancelTask(id);
        }

        return ResponseEntity.ok().build();
    }

    /**
     * 删除配置
     */
    @PostMapping("/delete")
    public ResponseEntity<?> deleteConfig(@RequestParam Long id) {
        SyncConfig config = configMapper.selectById(id);
        if (config == null) {
            return ResponseEntity.notFound().build();
        }

        scheduler.cancelTask(id);
        configMapper.deleteById(id);
        return ResponseEntity.ok().build();
    }

    /**
     * 手动触发同步
     */
    @PostMapping("/trigger")
    public ResponseEntity<?> triggerSync(@RequestParam Long id) {
        SyncConfig config = configMapper.selectById(id);
        if (config == null) {
            return ResponseEntity.notFound().build();
        }

        syncService.syncTable(config);
        return ResponseEntity.ok().build();
    }

    /**
     * 重新加载所有任务
     */
    @PostMapping("/reload")
    public ResponseEntity<?> reloadTasks() {
        scheduler.reloadAllTasks();
        return ResponseEntity.ok().build();
    }
}
